//
//  GQHOrderController.m
//  Xanthium
//
//  Created by GuanQinghao on 10/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model
#import "GQHOrderModel.h"

#pragma mark Object

#pragma mark View
#import "GQHOrderView.h"

#pragma mark Controller
#import "GQHOrderController.h"
#import "GQHPreExpenseController.h"
#import "GQHFinalExpenseController.h"
#import "GQHCommentController.h"
#import "GQHMapController.h"
#import "GQHContractDetailController.h"
#import "GQHReceiptController.h"
#import "GQHInvoiceController.h"


#import "GQHOrderDetailController.h"



#pragma mark CocoaPods

#pragma mark ----------Header End----------

@interface GQHOrderController () <GQHOrderViewDelegate>{
    
#pragma mark Data
    /// 请求参数
    NSMutableDictionary *parameters;
    /// 返回模型数组
    __block NSMutableArray<GQHOrderModel *> *orderModelArray;
    /// 选中的状态页标签
    NSInteger selectedTag;
#pragma mark View
    /// 自定义根视图
    GQHOrderView *rootView;
}

@end


@implementation GQHOrderController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHOrderView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    [self loadUserInterface];
    
    parameters = [NSMutableDictionary dictionary];
    if ([USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
        
        [parameters setObject:USER_GET_ID forKey:@"driverId"];
    } else {
        
        [parameters setObject:USER_GET_ID forKey:@"ownerId"];
    }
    
    if ([_qh_orderState isEqualToString:@"待装货"]) {
        
        UIButton *button = [UIButton new];
        button.tag = 100;
        [self checkOrderStatus:button];
    }
    if ([_qh_orderState isEqualToString:@"运输中"]) {
        
        UIButton *button = [UIButton new];
        button.tag = 101;
        [self checkOrderStatus:button];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"我的运单";
    self.qh_rightButton.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [rootView.qh_tableView.mj_header beginRefreshing];
    [rootView.qh_tableView.mj_footer endRefreshing];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

#pragma mark --Delegate
/// 点击列表项
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    DLog(@"查看订单详情");
    
    GQHOrderModel *orderModel = orderModelArray[indexPath.row];
    
    GQHOrderDetailController *orderDetailController = [[GQHOrderDetailController alloc] init];
    if (orderModel.qh_orderID && orderModel.qh_orderID.length > 0) {
        
        orderDetailController.qh_orderID = orderModel.qh_orderID;
        [self.navigationController pushViewController:orderDetailController animated:YES];
    } else {
        
        [self showToastWithText:@"订单ID为空"];
    }
}

/// (第四个按钮)确认装车或确认送达或评价
- (void)qh_loadedOrUnloadedOrComment:(UIButton *)sender {
    
    GQHOrderModel *orderModel = orderModelArray[sender.tag];
    
    if ([orderModel.qh_orderState isEqualToString:@"00"]) {
        DLog(@"订单状态:待司机确认装货");
        
        if ([USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"司机确认装车");
            
            NSMutableDictionary *para = [NSMutableDictionary dictionary];
            [para setObject:USER_GET_ID forKey:@"driverId"];
            [para setObject:orderModel.qh_orderNumber forKey:@"waybillAwb"];
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/buWaybill/1/waitPretend"];
            [GQHNetHelper qh_requestGET:APIURLString parameters:para success:^(NSNumber *code, NSString *message, NSDictionary *data) {
                DLog(@"%@---%@---%@",code,message,data);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (0 == [code integerValue]) {
                    
                    [self showToastWithText:message];
                    [rootView.qh_tableView.mj_header beginRefreshing];
                    [rootView.qh_tableView.mj_footer endRefreshing];
                } else {
                    
                    [self showToastWithText:message];
                }
            } failure:^(NSError *error) {
                
                NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
                [self showToastWithText:errorString];
            }];
        }
    }
    if ([orderModel.qh_orderState isEqualToString:@"01"]) {
        DLog(@"订单状态:待货主确认装货");
        if (![USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"货主确认装车");
            
            GQHPreExpenseController *preExpenseController = [[GQHPreExpenseController alloc] init];
            preExpenseController.qh_orderModel = orderModel;
            [self.navigationController pushViewController:preExpenseController animated:YES];
        }
    }
    if ([orderModel.qh_orderState isEqualToString:@"10"]) {
        DLog(@"订单状态:待司机确认送达");
        
        if ([USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"司机确认送达");
            
            GQHReceiptController *receiptController = [[GQHReceiptController alloc] init];
            receiptController.qh_orderModel = orderModel;
            receiptController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:receiptController animated:YES];
        }
    }
    if ([orderModel.qh_orderState isEqualToString:@"11"]) {
        DLog(@"订单状态:待货主确认送达");
        
        if (![USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"货主确认送达");
            
            GQHFinalExpenseController *finalExpenseController = [[GQHFinalExpenseController alloc] init];
            finalExpenseController.qh_orderModel = orderModel;
            [self.navigationController pushViewController:finalExpenseController animated:YES];
        }
    }
    if ((selectedTag == 104) && [orderModel.qh_orderState isEqualToString:@"20"]) {
        DLog(@"订单状态:已完成");
        
        if ([USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"司机开发票");
            
            GQHInvoiceController *invoiceController = [[GQHInvoiceController alloc] init];
            if ([orderModel.qh_invoiceState isEqualToString:ORDER_STATUS_I0]) {
                
                invoiceController.qh_editable = YES;
            } else {
                
                invoiceController.qh_editable = NO;
            }
            invoiceController.qh_orderModel = orderModel;
            invoiceController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:invoiceController animated:YES];
        }
    }
    if ((selectedTag == 102) && [orderModel.qh_orderState isEqualToString:@"20"]) {
        DLog(@"订单状态:待评价");
        
        if ([USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"司机评价货主");
            
            GQHCommentController *commentController = [[GQHCommentController alloc] init];
            commentController.qh_orderModel = orderModel;
            commentController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:commentController animated:YES];
        } else {
            DLog(@"货主评价司机");
            
            GQHCommentController *commentController = [[GQHCommentController alloc] init];
            commentController.qh_orderModel = orderModel;
            commentController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:commentController animated:YES];
        }
    }
}

/// (第三个按钮)取消订单或在途追踪
- (void)qh_cancelOrMap:(UIButton *)sender {
    
    GQHOrderModel *orderModel = orderModelArray[sender.tag];
    if ([orderModel.qh_orderState isEqualToString:@"00"]) {
        DLog(@"订单状态:待司机确认装货");
        if (![USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"货主取消订单");
            
            NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/buWaybill/1/cancel"];
            NSMutableDictionary *para = [NSMutableDictionary dictionary];
            [para setObject:orderModel.qh_orderNumber forKey:@"waybillAwb"];
            
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [GQHNetHelper qh_requestGET:APIURLString parameters:para success:^(NSNumber *code, NSString *message, NSDictionary *data) {
                DLog(@"%@---%@---%@",code,message,data);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (0 == [code integerValue]) {
                    
                    [self showToastWithText:message];
                    
                    [rootView.qh_tableView.mj_header beginRefreshing];
                    [rootView.qh_tableView.mj_footer endRefreshing];
                } else {
                    
                    [self showToastWithText:message];
                }
            } failure:^(NSError *error) {
                
                NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
                [self showToastWithText:errorString];
            }];
        }
    }
    if ([orderModel.qh_orderState isEqualToString:@"10"] || [orderModel.qh_orderState isEqualToString:@"11"]) {
        DLog(@"订单状态:待司机确认送达 或 待货主确认送达");
        if (![USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
            DLog(@"货主在途跟踪");
            
            GQHMapController *mapController = [[GQHMapController alloc] init];
            mapController.qh_departureLatitude = orderModel.qh_departureLatitude;
            mapController.qh_departureLongitude = orderModel.qh_departureLongitude;
            mapController.qh_destinationLatitude = orderModel.qh_destinationLatitude;
            mapController.qh_destinationLongitude = orderModel.qh_destinationLongitude;
            mapController.qh_truckID = orderModel.qh_driverID;
            mapController.startPlace = orderModel.qh_departure;
            mapController.endPlace = orderModel.qh_destination;
            mapController.loadingTime = orderModel.qh_loadingTime;
            [self.navigationController pushViewController:mapController animated:YES];
        }
    }
}

/// (第二个按钮)拨打电话
- (void)qh_dialMobile:(UIButton *)sender {
    GQHOrderModel *orderModel = orderModelArray[sender.tag];
    if ([USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
        DLog(@"联系货主");
        
        if (orderModel.qh_ownerMobile && [orderModel.qh_ownerMobile qh_isValidMobile]) {
            
            [self qh_dialWithMobile:orderModel.qh_ownerMobile];
        } else {
            
            [self showToastWithText:@"货主联系方式不正确"];
        }
    } else {
        DLog(@"联系司机");
        
        if (orderModel.qh_driverMobile && [orderModel.qh_driverMobile qh_isValidMobile]) {
            
            [self qh_dialWithMobile:orderModel.qh_driverMobile];
        } else {
            
            [self showToastWithText:@"司机联系方式不正确"];
        }
    }
}

/// (第一个按钮)查看协议内容
- (void)qh_checkContract:(UIButton *)sender {
    DLog(@"查看协议");
    
    GQHOrderModel *orderModel = orderModelArray[sender.tag];
    if (orderModel.qh_contractID && orderModel.qh_contractID.length > 0) {
        
        GQHContractDetailController *contractDetailController = [[GQHContractDetailController alloc] init];
        contractDetailController.qh_contractID = orderModel.qh_contractID;
        contractDetailController.qh_acceptable = YES;
        contractDetailController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:contractDetailController animated:YES];
    } else {
        
        [self showToastWithText:@"协议不存在"];
    }
}

#pragma mark --TargetMethod

#pragma mark --PrivateMethod
/// 刷新订单列表
- (void)checkOrderStatus:(UIButton *)sender {
    
    for (NSInteger i = 0; i < 5; i++) {
        
        if (i == sender.tag - 100) {
            
            UIButton *button = (UIButton *)[rootView viewWithTag:(100 + i)];
            [button setTitleColor:kRedColor forState:UIControlStateNormal];
            
            UIView *indicatorView = [rootView viewWithTag:(200 + i)];
            indicatorView.hidden = NO;
        } else {
            
            UIButton *button = (UIButton *)[rootView viewWithTag:(100 + i)];
            [button setTitleColor:kDarkBlackColor forState:UIControlStateNormal];
            
            UIView *indicatorView = [rootView viewWithTag:(200 + i)];
            indicatorView.hidden = YES;
        }
    }
    
    switch (sender.tag) {
            
        case 100: {
            
            [parameters setObject:@"0" forKey:@"waybillState"];
            [parameters setObject:@"" forKey:@"reviewedState"];
            [parameters setObject:@"" forKey:@"evaluateState"];
        }
            break;
        case 101: {
            
            [parameters setObject:@"1" forKey:@"waybillState"];
            [parameters setObject:@"" forKey:@"reviewedState"];
            [parameters setObject:@"" forKey:@"evaluateState"];
        }
            break;
        case 102: {
            
            [parameters setObject:@"2" forKey:@"waybillState"];
            if ([USER_GET_TYPE isEqualToString:USER_TYPE_D]) {
                
                [parameters setObject:@"02" forKey:@"reviewedState"];
                [parameters setObject:@"" forKey:@"evaluateState"];
            } else {
                
                [parameters setObject:@"02" forKey:@"evaluateState"];
                [parameters setObject:@"" forKey:@"reviewedState"];
            }
        }
            break;
        case 103: {
            
            [parameters setObject:@"3" forKey:@"waybillState"];
            [parameters setObject:@"" forKey:@"reviewedState"];
            [parameters setObject:@"" forKey:@"evaluateState"];
        }
            break;
        case 104: {
            
            [parameters setObject:@"2" forKey:@"waybillState"];
            [parameters setObject:@"" forKey:@"reviewedState"];
            [parameters setObject:@"" forKey:@"evaluateState"];
        }
            break;
        default:
            break;
    }
    
    [self fetchOrdersWithParameters:parameters];
    selectedTag = sender.tag;
    rootView.qh_selectedTag = sender.tag;
    [rootView.qh_tableView.mj_header beginRefreshing];
    [rootView.qh_tableView.mj_footer endRefreshing];
}

/// 获取订单列表数据
- (void)fetchOrdersWithParameters:(NSMutableDictionary *)parameters {
    
    __block int page = 1;
    [parameters setObject:ROWS forKey:@"rows"];
    
    rootView.qh_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        page = 1;
        [parameters setObject:[NSNumber numberWithInt:page] forKey:@"page"];
        
        [GQHOrderModel qh_fetchOrdersWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHOrderModel *> *orders) {
            
            if (status) {
                
                orderModelArray = [NSMutableArray arrayWithArray:orders];
                rootView.qh_orderModelArray = orderModelArray;
                [rootView.qh_tableView reloadData];
                
            } else {
                
                [self showToastWithText:message];
            }
            [rootView.qh_tableView.mj_header endRefreshing];
            
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
            [rootView.qh_tableView.mj_header endRefreshing];
        }];
    }];
    
    rootView.qh_tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        page++;
        [parameters setObject:[NSNumber numberWithInt:page] forKey:@"page"];
        
        [GQHOrderModel qh_fetchOrdersWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHOrderModel *> *orders) {
            
            if (status) {
                
                if (orders && orders.count > 0) {
                    
                    [orderModelArray addObjectsFromArray:orders];
                    rootView.qh_orderModelArray = orderModelArray;
                    [rootView.qh_tableView reloadData];
                    [rootView.qh_tableView.mj_footer endRefreshing];
                } else {
                    
                    [rootView.qh_tableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                
                [self showToastWithText:message];
                [rootView.qh_tableView.mj_footer endRefreshing];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
            [rootView.qh_tableView.mj_footer endRefreshing];
        }];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View
- (void)loadUserInterface {
    
    NSArray *orderStatusArray = @[@"待装货",@"运输中",@"待评价",@"已取消",@"已完成"];
    
    UIView *containerView = [[UIView alloc] init];
    containerView.backgroundColor = kLightGrayColor;
    [rootView addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(rootView.qh_navigationBarHeight + rootView.qh_statusBarHeight);
        make.left.and.right.mas_equalTo(rootView);
        make.height.mas_equalTo(60);
    }];
    
    CGFloat itemWidth = 0.2 * rootView.qh_width;
    CGFloat itemHeight = 50;
    
    for (NSInteger i = 0; i < 5; i++) {
        
        CGFloat leftValue = i * itemWidth;
        UIButton *orderStatusButtton = [UIButton buttonWithType:UIButtonTypeCustom];
        orderStatusButtton.backgroundColor = kWhiteColor;
        orderStatusButtton.tag = 100 + i;
        orderStatusButtton.titleLabel.font = kDefaultFont;
        [orderStatusButtton setTitle:orderStatusArray[i] forState:UIControlStateNormal];
        if (0 == i) {
            
            [orderStatusButtton setTitleColor:kRedColor forState:UIControlStateNormal];
        } else {
            
            [orderStatusButtton setTitleColor:kDarkBlackColor forState:UIControlStateNormal];
        }
        [orderStatusButtton addTarget:self action:@selector(checkOrderStatus:) forControlEvents:UIControlEventTouchUpInside];
        [containerView addSubview:orderStatusButtton];
        [orderStatusButtton mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(containerView);
            make.left.mas_equalTo(leftValue);
            make.size.mas_equalTo(CGSizeMake(itemWidth, itemHeight));
        }];
        
        // splitor indicator separator
        UIView *indicatorView = [[UIView alloc] init];
        indicatorView.backgroundColor = kRedColor;
        if (0 == i) {
            
            indicatorView.hidden = NO;
        } else {
            
            indicatorView.hidden = YES;
        }
        indicatorView.tag = 200 + i;
        [orderStatusButtton addSubview:indicatorView];
        [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.and.bottom.mas_equalTo(orderStatusButtton);
            make.size.mas_equalTo(CGSizeMake(itemWidth, 2));
        }];
    }
}

@end
